package com.liuyu.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 自定义消息序列化，通过实现MessageConverter接口
 * 处理方式可分为json方式序列化和字符串方式序列化
 *
 * 通过注入messageConverter对象指定该类的实例为处理方式
 */
public class CustomMessageConverter implements MessageConverter {

    private final ObjectMapper objectMapper = new ObjectMapper();

    //java对象到message
    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        try {
            if (object instanceof String) {
                messageProperties.setContentType("text/plain");
                return new Message(((String) object).getBytes(StandardCharsets.UTF_8), messageProperties);
            } else {
                // JSON 序列化
                messageProperties.setContentType("application/json");
                return new Message(objectMapper.writeValueAsBytes(object), messageProperties);
            }
        } catch (JsonProcessingException e) {
            throw new MessageConversionException("Error converting object to JSON: " + object.getClass().getName(), e);
        }
    }

    //消息转为对象
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        String contentType = message.getMessageProperties().getContentType();
        if ("application/json".equals(contentType)) {
            try {
                return objectMapper.readValue(message.getBody(), Map.class); // 可改成具体类型
            } catch (Exception e) {
                throw new MessageConversionException("Error converting message from JSON", e);
            }
        }
        return new String(message.getBody(), StandardCharsets.UTF_8);
    }
}
